package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.SupplierCategory;
import com.wing.purchase.model.request.SupplierCategoryForm;
import com.wing.purchase.service.SupplierCategoryService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * @author
 */
@Validated
@Api(value = "Admin-供应商分类管理", tags = "#/purchase/supplierCategory")
@RestController("supplierCategoryController")
@RequestMapping("purchase/admin/supplierCategory")
@RequiredArgsConstructor
public class SupplierCategoryController {

    private final SupplierCategoryService supplierCategoryService;


    /**
     * 查询所有供应商分类
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param name
     * @return
     */
    @ApiOperation(value = "查询所有供应商分类", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SupplierCategory> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "9999") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , String name
    ) {

        Page<SupplierCategory> pg = new Page<>(page, limit);
        QueryWrapper<SupplierCategory> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }

        IPage<SupplierCategory> list = supplierCategoryService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 添加供应商分类
     * @param supplierCategoryForm
     * @return
     */
    @ApiOperation(value = "添加供应商分类", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "supplierCategoryAdd")
    public JsonResult add(@Validated(SupplierCategoryForm.Add.class) SupplierCategoryForm supplierCategoryForm) {
        //为终极分类时不允许添加子类
        if (supplierCategoryForm.getParentId() != null) {
            SupplierCategory parent = supplierCategoryService.getById(supplierCategoryForm.getParentId());
            if (parent != null && parent.getIsFinal() != null && parent.getIsFinal()) {
                return JsonResult.fail("添加失败，该上级分类为终极分类");
            }
        }
        if (supplierCategoryService.add(supplierCategoryForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    /**
     * 修改供应商分类
     * @param supplierCategoryForm
     * @return
     */
    @ApiOperation(value = "修改供应商分类", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "supplierCategoryUpdate")
    public JsonResult update(@Validated(SupplierCategoryForm.Update.class) SupplierCategoryForm supplierCategoryForm) {
        SupplierCategory supplierCategory = supplierCategoryService.getById(supplierCategoryForm.getId());
        if (supplierCategory == null) {
            return JsonResult.fail("修改失败！");
        }
        if (supplierCategoryForm.getParentId() != null) {
            SupplierCategory parent = supplierCategoryService.getById(supplierCategoryForm.getParentId());
            if (parent != null && parent.getIsFinal() != null && parent.getIsFinal()) {
                return JsonResult.fail("修改失败，该上级分类为终极分类");
            }
            int count = supplierCategoryService.count(new QueryWrapper<SupplierCategory>().eq("parent_id", supplierCategory.getId()));
            if (count > 0 && supplierCategoryForm.getIsFinal()) {
                return JsonResult.fail("该分类有下级分类，不可置为终极分类");
            }
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(SupplierCategory.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierCategoryForm, supplierCategory, copyOptions);
        if (supplierCategoryService.updateById(supplierCategory)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    /**
     * 删除供应商分类
     * @param supplierCategoryId
     * @return
     */

    @ApiOperation(value = "删除供应商分类", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierCategoryId", value = "供应商分类id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long supplierCategoryId) {
        try {
            if (supplierCategoryService.delete(supplierCategoryId)) {
                return JsonResult.success("删除成功");
            }
            return JsonResult.fail("删除失败");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getMessage());
        }
    }


    /**
     * 启用
     * @param supplierCategoryForm
     * @return
     */
    @ApiOperation(value = "启用", notes = "启用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(SupplierCategoryForm.Add.class) SupplierCategoryForm supplierCategoryForm) {
        if (supplierCategoryService.enable(supplierCategoryForm.getId()) >= 0) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    /**
     * 停用
     * @param supplierCategoryForm
     * @return
     */
    @ApiOperation(value = "停用", notes = "停用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(SupplierCategoryForm.Add.class) SupplierCategoryForm supplierCategoryForm) {
        if (supplierCategoryService.disable(supplierCategoryForm.getId()) >= 0) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getTreeData")
    public JsonResult getTreeData(Long selectId) {
        return supplierCategoryService.getTreeData(selectId);
    }


    /**
     * 异步同步供应商分类
     * @return
     */
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/syncGetSupplierList")
    public JsonResult syncGetSupplierList() {
        return supplierCategoryService.syncGetSupplierList();
    }
}
